package com.lepu.app.fun.index.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.adapter.IndexHotArticleAdapter;
import com.lepu.app.fun.knowledge.bean.Article;
import com.lepu.app.fun.my.bean.BeanPubContent;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentIndexMore extends BaseFragment implements AsyncRequest,
		OnRefreshListener, OnLoadListener {

	private View mMainView = null;
	private boolean mInitDataSuccess = false;// 是否加载完数据

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private IndexHotArticleAdapter mDataAdapter = null;
	private ArrayList<Article> mDataArrayList = null;
	private int mCurrentPage = 1;

	private int mPeriod = 1;
	private int mSortBy = 1;// 1：发布时间 2：最多阅读
	private String mRefreshTime = "";

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.app_fragment_list_layout, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据

				showFirstLoadDataLayout(true);
				request(false);
			}
		}
	}

	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.mMainView.findViewById
	 * 不能使用mMainView.findViewById，否则程序会闪退的
	 */
	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("ResourceAsColor")
	private void init() {

		mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView
				.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		Bundle data = getArguments();
		mPeriod = data.getInt("Period");
		mSortBy = data.getInt("SortBy");

		mDataListView.setOnItemClickListener(mOnItemClickListener);
	}

	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = Setting.getIndexDayArticleMoreUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);

			params.put("Period", mPeriod);
			params.put("RefreshTime", mRefreshTime);
			params.put("SortBy", mSortBy);
			params.put("SortDirection", "DESC");
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true);

	}

	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) mMainView
				.findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					noDataLayout.setVisibility(View.VISIBLE);
				}
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView
				.findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}

				LinearLayout noDataLayout = (LinearLayout) mMainView
						.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			if (getActivity() == null) {
				return;
			}

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<Article> dataList = (ArrayList<Article>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mInitDataSuccess = true;
					mDataArrayList = dataList;

					showHideNoDataLayout(false);
				} else {
					//UIHelper.showToast(getActivity(), R.string.no_data);

					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}

					showHideNoDataLayout(true);
				}

				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<Article>();
				}

				ImageView tempImageView = new ImageView(getActivity());
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new IndexHotArticleAdapter(getActivity(),
						mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showFirstLoadDataLayout(false);

				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanPubContent> dataMoreList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// int position = mDataArrayList.size()-1;
					// mMaxTopicId =
					// Integer.valueOf(mDataArrayList.get(position).TopicID);
					// LogUtilBase.LogD(TAG, "mMaxTopicId == >>"+mMaxTopicId);

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(getActivity(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Article item = mDataArrayList.get(position);
			MyNetUtil.getInstance().requestArticleDetail(
					(BaseFragmentActivity) getActivity(), item.ArticleID,
					item.DisplayType, item.ContentType,"");
		}
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {

			Article article = Article.parseSimpleData((String) data);
			if (article != null) {
				mRefreshTime = article.RefreshTime;
			}

			// 解析json data
			ArrayList<Article> dataArraylist = Article
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<Article> dataMoreArraylist = Article
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {

				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					Article item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}
	}

}
